﻿using Core.AdditionalInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    public static class LogicExtentions
    {
        public static List<T> CreateTree<T>(this IEnumerable<T> entities) where T : class, ITree
        {
            var itreeList = entities.Where(x => x.ParentId == 0);

            var resultTreeList = new List<ITree<T>>();

            foreach (var entity in itreeList)
            {               
                entity.IsRoot = true;
                FillBranch<T>((ITree<T>)entity, entities);
                resultTreeList.Add((ITree<T>)entity);              
            }


            return resultTreeList.ConvertAll(x => (T)x);
        }

        #region private methods

        private static void FillBranch<T>(ITree<T> rootNode, IEnumerable<T> allNodes) where T : class, ITree
        {
            var childEntities = allNodes.Where(x => x.ParentId == rootNode.Id);
            if (childEntities.Count() > 0)
            {
                rootNode.HasChild = true;
                rootNode.ChildEntities = childEntities;

                foreach (var childNode in rootNode.ChildEntities)
                {
                    FillBranch<T>((ITree<T>)childNode, allNodes);
                }
            }
        }

        #endregion
    }
}
